<?php
/**
 * @file cmstags.php
 * @author CaoQiCheng
 * @date 2017年2月7日 下午17:16:11
 * @brief
 */

namespace haibao\jiepai\data;

use haibao\app\business\BusinessException;

class Comment extends \haibao\jiepai\data\BaseMysql
{

    public function __construct()
    {
        parent::__construct('\haibao\jiepai\model\data\comment\CmsComment');
    }

    public function getCommentList($query)
    {
        return $this->getAll($query);
    }

    public function delCommentAudit($commentId)
    {
        $sql = "update cms_comment_audit set Flag=-1 where Type=1 and TypeID=%s";
        $this->query($sql, array($commentId));
    }

    public function addPoint($commentId, $type)
    {
        if ($type == 1) {
            $sql = "update cms_comment set IsBest=1 where CommentID=%s";
            $this->query($sql, array($commentId));
        }
        if ($type == 2) {
            $sql = "update cms_comment_reply set IsBest=1 where ReplyID=%s";
            $this->query($sql, array($commentId));
        }

    }

    public function UpdateCommentReplySensitive($type, $typeId, $sensitiveWords)
    {
        if ($type == 'comment') {
            $sql = "UPDATE cms_comment SET SensitiveWords = '" . $sensitiveWords . "' where CommentID = " . $typeId;
            $this->query($sql);
        } else if ($type == 'reply') {
            $sql = "UPDATE cms_comment_reply SET SensitiveWords = '" . $sensitiveWords . "' where ReplyID = " . $typeId;
            $this->query($sql);
        }
    }

    /**
     * 增加合作的品牌关联
     */
    public function saveCommentPictures($replyId, $imageIdArr)
    {
        if (!$replyId) {
            return false;
        }

        if (isset($imageIdArr) && $imageIdArr) {
            $sql = 'insert into cms_comment_pictures(PictureID,Type,`Index`,TypeID,Flag) values ';
            $arrSql = $arrValues = array();
            $i = 0;
            foreach ($imageIdArr as $key => $val) {
                array_push($arrSql, '(%s,%s,%s,%s,%s)');
                array_push($arrValues, $val);
                array_push($arrValues, 2);
                array_push($arrValues, $i);
                array_push($arrValues, $replyId);
                array_push($arrValues, 0);
                $i++;
            }
            if ($arrSql && $arrValues) {
                $sql .= implode(',', $arrSql);
                $this->query($sql, $arrValues);
            }
        }
    }

    public function saveReply($replyModel)
    {
        $this->add($replyModel);
    }

    /**
     * 根据id插入数组
     */
    public function checkCommentByIds($commentIds, $userId, $commentCheck)
    {
        if ($commentIds) {
            $commentIds = implode(',', $commentIds);
            $sql = "update cms_comment set AuditStatus=%s,AuditTime=%s,AuditUserID=%s where CommentID in (" . $commentIds . ")";
            $this->query($sql, array($commentCheck, new \DateTime(), $userId));

        }
    }

    public function checkReplyByIds($replyIdArr, $userId, $commentCheck)
    {
        if ($replyIdArr) {
            $replyIdArr = implode(',', $replyIdArr);
            $sql = "update cms_comment_reply set AuditStatus=%s,AuditTime=%s,AuditUserID=%s where ReplyID in (" . $replyIdArr . ")";
            $this->query($sql, array($commentCheck, new \DateTime(), $userId));
        }
    }

    /**
     *
     * 获取马甲用户 id与姓名
     */
    public function getMajiaUser($userId)
    {
        $userList = array();
        $sql = "SELECT u.UserID,u.NickName
    	from cms_users as u
    	WHERE u.UserID IN(SELECT cau.UserID
    	from  cms_admin_users as cau
    	where cau.AdminID = %s)";
        $result = $this->query($sql, array($userId));

        while ($row = $result->fetch_assoc()) {
            $userList[] = $row;
        }

        return $userList;
    }

    public function updateCommentReplyForAduit($replyId, $status, $userId)
    {
        $time = new \DateTime();
        $sql = "update cms_comment_reply set AuditStatus=%s,AuditTime=%s,AuditUserID=%s where ReplyID =%s";
        $this->query($sql, array($status, $time, $userId, $replyId));
    }

    /**
     * 删除审核
     */
    public function delReplyAudit($commentId)
    {
        $sql = "update cms_comment_reply set AuditStatus=0,AuditTime=NULL,AuditUserID=NULL where ReplyID =%s";
        $this->query($sql, array($commentId));
        $sql1 = "update cms_comment_audit set Flag=-1 where Type =2 and TypeID=%s";
        $this->query($sql1, array($commentId));
    }

    /**
     * 获取comment和comment_reply所有数据并且整合
     */
    public function getCommentListBySql($option)
    {
        $commentListData = array();
        $parameter = $parameter1 = array();
        $sqlSelect = "SELECT v.*,u.NickName,f.ServerFileName as Avatar,c1.ContentInfo as Picture,u.Title ";
        $sqlCount = "SELECT count(*) as count ";
        $sql = 'FROM (SELECT  co.ReplyNum as ReplyNum,co.PraiseNum as PraiseNum,co.CommentID as ID,null as RepliedID,co.CommentID,co.TypeID as ArticleID,1 as Type,co.UserID,co.Content,co.CreateTime as Time,co.AuditStatus,co.Flag,au.AdminID,co.SensitiveWords,co.IsBest 
    	FROM cms_comment co 
    	LEFT JOIN cms_articles a1 ON co.TypeID=a1.ArticleID LEFT JOIN cms_admin_users au ON a1.EditorID=au.UserID AND au.Type="P" WHERE co.Type=0 
    	UNION ALL 
    	SELECT 0 as ReplyNum,0 as PraiseNum,r.ReplyID as ID,r.RepliedID,r.CommentID,c.TypeID as ArticleID,2 as Type,r.UserID,r.Content,r.ReplyTime as Time,r.AuditStatus,r.Flag,au1.AdminID,r.SensitiveWords,r.IsBest  
    	FROM cms_comment_reply r LEFT JOIN cms_comment c ON r.CommentID=c.CommentID 
    	LEFT JOIN cms_admin_users au1 ON r.RepliedUserID=au1.UserID 
    	) as v 
    	LEFT JOIN cms_admin_users u1 ON u1.ID=(SELECT ID FROM cms_admin_users u2 WHERE u2.UserID=v.UserID LIMIT 1) 
    	LEFT JOIN cms_users u ON v.UserID=u.UserID LEFT JOIN cms_files f ON u.AvatarID=f.FileID 
    	LEFT JOIN cms_article_content c1 ON c1.ArticleID=v.ArticleID AND c1.Type=0
    	WHERE 1=1 ';

        if (isset($option['auditStatus'])) {
            $sql .= 'and v.AuditStatus=%s ';
            array_push($parameter, $option['auditStatus']);
            array_push($parameter1, $option['auditStatus']);
        }
        if (isset($option['sensitiveWords'])) {
            $sql .= '  and v.SensitiveWords is not null and v.SensitiveWords!=""  and v.AuditStatus!=1 ';
        }
        if (isset($option['articleId'])) {
            $sql .= ' and v.ArticleID=%s ';
            array_push($parameter, $option['articleId']);
            array_push($parameter1, $option['articleId']);
        }
        if (isset($option['startDate']) && isset($option['endDate'])) {
            $sql .= ' and v.Time between %s and %s ';
            array_push($parameter, $option['startDate']);
            array_push($parameter, $option['endDate']);

            array_push($parameter1, $option['startDate']);
            array_push($parameter1, $option['endDate']);

        }
        if (isset($option['commentFlag'])) {
            $sql .= ' and v.Flag=%s ';
            array_push($parameter, $option['commentFlag']);

            array_push($parameter1, $option['commentFlag']);
        }
        if (isset($option['lookSign'])) {
            $sql .= 'and v.AdminID=%s ';
            array_push($parameter, $option['lookSign']);
            array_push($parameter1, $option['lookSign']);
        }
        if (isset($option['excludeAdmin'])) {
            $sql .= 'and u1.AdminID is NULL ';
        }

        if (isset($option['articleIdInLine'])) {
            $sql .= 'and v.ArticleID=%s ';
            array_push($parameter, $option['articleIdInLine']);
            array_push($parameter1, $option['articleIdInLine']);
        }
        if (isset($option['commentId'])) {
            $sql .= 'and v.ID=%s ';
            array_push($parameter, $option['commentId']);
            array_push($parameter1, $option['commentId']);
        }
        if (isset($option['userId'])) {
            $sql .= ' and  v.UserID=%s ';
            array_push($parameter, $option['userId']);
            array_push($parameter1, $option['userId']);
        }
        if (isset($option['content'])) {
            $sql .= "and v.Content like %s ";
            array_push($parameter, '%' . $option['content'] . '%');
            array_push($parameter1, '%' . $option['content'] . '%');
        }

        if(isset($option['orderType'])){
            $sql .= ' ORDER BY v.PraiseNum DESC ';
        }else{
            $sql .= ' ORDER BY v.Time DESC ';
        }

        $sqlCount .= $sql;
        if (isset($option['page'])) {
            $page = $option['page'] - 1;
            $sql .= ' limit ' . $page * 20 . ',20 ';
        }

        $sqlSelect .= $sql;


        $result = $this->query($sqlSelect, $parameter);
        $resultCount = $this->query($sqlCount, $parameter1);

        while ($row = $result->fetch_assoc()) {
            $commentListData[] = $row;
        }
        while ($row = $resultCount->fetch_assoc()) {
            $commentListData['count'] = $resultCount->getData('count');
        }
        return $commentListData;
    }


    /**
     * @param $commentId 评论Id
     * @param $commentTpe 评论类型
     */
    // TODO : 取cms数据库
    public function getCommentPictures($commentId, $commentType)
    {

        $sql = 'SELECT p.PictureID FROM cms_comment_pictures p ' .
            ' where p.TypeID=%s and p.Type=%s';
        $result = $this->query($sql, array($commentId, $commentType));
        $list = array();
        while ($row = $result->fetch_assoc()) {
            array_push($list, $result->getData('PictureID'));
        }
        return $list;
    }

    public function getCommentAudit($commentId, $commentType)
    {

        $sql = 'SELECT a.*,c.`Name` FROM cms_comment_audit a LEFT JOIN cms_admin c ON a.UserID=c.AdminID WHERE a.TypeID=%s AND a.Type=%s and a.Flag=0';
        return $this->query($sql, array((int)$commentId, (int)$commentType))->fetch_assoc();
    }

    public function createCommentAudit($optionData)
    {
        $sql = 'INSERT INTO cms_comment_audit (Category,Reason,UserID,`Type`,TypeID,Status) values (%s,%s,%s,%s,%s,%s)';
        $this->query($sql, $optionData);

    }

    public function updateCommentAuditStatus($optionData)
    {

        $sql = '';
        if ($optionData['Type'] == 1) {
            $sql = 'update cms_comment set AuditStatus=%s where CommentID = %s';
        } else {
            $sql = 'update cms_comment_reply set AuditStatus=%s where ReplyID = %s';

        }
        $this->query($sql, array($optionData['Status'], $optionData['TypeID']));

    }

    /***
     * @param unknown $commentId
     * @param unknown $source
     */
    public function updateCommentScores($commentId, $source)
    {
        $sql = "UPDATE cms_comment SET Scores = Scores + " . $source . " WHERE CommentID = (" . $commentId . ")";
        $result = $this->query($sql);
        return $result->getAffectRow();
    }

    // Type   3，点赞文章  4，点赞评论  5，图片点赞
    function pushPraiseMsg($commentIdArr, $type, $fromUserId)
    {
        // 1,找出ToUserID和点赞users  2,入库  3,统计未读数量  4,推送
        if ($type == 3) {
            $sql = 'SELECT ArticleID as TypeId,EditorID as ToUserID FROM cms_articles WHERE ArticleID IN (' . $commentIdArr . ')';
        } else if ($type == 4 || $type == 7) {
            $sql = 'SELECT CommentID as TypeId,UserID as ToUserID FROM cms_comment WHERE CommentID IN (' . $commentIdArr . ')';
        } else if ($type == 6 || $type == 8) {
            $sql = 'SELECT ReplyID as TypeId,UserID as ToUserID FROM cms_comment_reply WHERE ReplyID IN (' . $commentIdArr . ')';
        }
        $result = $this->query($sql);
        $toUserID = array();
        while ($row = $result->fetch_assoc()) {
            if ($row['ToUserID']) {
                if ($fromUserId == $row['ToUserID']) {
                    return;
                }
                $useSql = 'select * from cms_messages_praise where ToUserID=%s AND FromUserID=%s AND TypeID =%s AND Type=%s';
                $data = $this->query($useSql, array($row['ToUserID'], $fromUserId, $row['TypeId'], $type));
                if ($data->getAffectRow() == 0) {
                    $mesSql = 'insert into cms_messages_praise (ToUserID,FromUserID,TypeID,Type) VALUES(%s,%s,%s,%s)';
                    $this->query($mesSql, array($row['ToUserID'], $fromUserId, $row['TypeId'], $type));
                }
                array_push($toUserID, $row['ToUserID']);
            }
        }
        return $this->CountPraiseMessage($toUserID);
    }

    function CountPraiseMessage($toUserID, $isOld = false)
    {
        $dataInfo = array();
        if ($toUserID) {
            $str = preg_replace('/(\d+)/', '%s', implode(',', $toUserID));
            $sql = "SELECT count(*) as count,ToUserID FROM cms_messages_praise WHERE MessageID IS NULL AND ToUserID IN (" . $str . ")";
            if ($isOld) $sql .= ' and Type!=6';
            $sql .= ' GROUP BY ToUserID';
            $result = $this->query($sql, $toUserID);
            while ($result->fetch_assoc()) {
                $dataInfo[$result->getData('ToUserID')] = $result->getData('count');
            }
        }
        return $dataInfo;
    }

    public function deleteMyComment($commentId, $userId, $type)
    {
        if ($type == 1) {//删除评论
            $sql = "UPDATE cms_comment SET Flag = -1 WHERE CommentID=%s and UserID=%s";
            $this->query($sql, array($commentId, $userId));
        }
        if ($type == 2) {//删除回复
            $sql = "UPDATE cms_comment_reply SET Flag = -1 WHERE ReplyID=%s and UserID=%s";
            $this->query($sql, array($commentId, $userId));
        }
        return true;
    }

    public function getReplyInfo($replyId)
    {
        $sql = "SELECT cr.*, cr.ReplyTime AS CreateTime,c.Type as CommentType FROM cms_comment_reply cr LEFT JOIN cms_comment c on c.CommentID = cr.CommentID WHERE cr.ReplyID = %s";
        return $this->query($sql, array($replyId))->fetch_assoc();
    }


    public function getMyComments($userId, $cursor, $version = null)
    {
        if (version_compare($version, \haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LAST_SUPPORT_VERSION_450)) >= 0) {
//            $sql = "SELECT c.ID,c.CreateTime,c.Type,c.AuditStatus,c.Flag from (SELECT CommentID as ID,UserID,CreateTime,1 as Type,AuditStatus,Flag from cms_comment UNION ALL SELECT ReplyID as ID,UserID,ReplyTime,2 as Type,AuditStatus,Flag from cms_comment_reply ) c WHERE c.UserID = %s" .
//                " AND c.Flag = 0 ORDER BY c.CreateTime DESC limit " . ($cursor - 1) * \haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LARGE_ARTICLE_PAGE_SIZE) . ',' . \haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LARGE_ARTICLE_PAGE_SIZE);
            $sql = 'SELECT DISTINCT c.ID,c.CreateTime,c.Type,c.AuditStatus,c.Flag,c.CommentType FROM (';
            $sql .= ' SELECT CommentID AS ID,UserID,CreateTime,1 AS Type,AuditStatus,Flag,Type as CommentType FROM cms_comment where UserID=' . $userId . ' and Flag=0 ';
            $sql .= ' UNION ALL ';
            $sql .= ' select ttt.ID,ttt.UserID,ttt.ReplyTime,2 AS Type,ttt.AuditStatus,ttt.Flag,ttt.CommentType from (select t.ReplyID as ID,t.UserID,t.ReplyTime,t.AuditStatus,t.Flag,tt.Type as CommentType from cms_comment_reply as t left join cms_comment as tt on t.CommentID=tt.CommentID where t.UserID=' . $userId . ' and tt.Flag=0) ttt ';
            $sql .= ' ) c WHERE c.UserID = ' . $userId . ' AND c.Flag = 0 ORDER BY c.CreateTime DESC LIMIT ' . ($cursor - 1) * \haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LARGE_ARTICLE_PAGE_SIZE) . ',' . \haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LARGE_ARTICLE_PAGE_SIZE);
        } else {
            $sql = 'SELECT DISTINCT c.ID,c.CreateTime,c.Type,c.AuditStatus,c.Flag,c.CommentType FROM (';
            $sql .= ' SELECT CommentID AS ID,UserID,CreateTime,1 AS Type,AuditStatus,Flag,Type as CommentType FROM cms_comment where UserID=' . $userId . ' and Flag=0 AND Type=0';
            $sql .= ' UNION ALL ';
            $sql .= ' SELECT t.ReplyID AS ID,t.UserID,t.ReplyTime,2 AS Type,t.AuditStatus,t.Flag,tt.Type as CommentType FROM cms_comment_reply as t left join cms_comment as tt on t.CommentID=t.CommentID where t.UserID=' . $userId . ' and t.Flag=0 AND tt.Type=0';
            $sql .= ' ) c WHERE c.UserID = ' . $userId . ' AND c.Flag = 0 AND c.CommentType=0 ORDER BY c.CreateTime DESC LIMIT ' . ($cursor - 1) * \haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LARGE_ARTICLE_PAGE_SIZE) . ',' . \haibao\classlibrary\jiepai\Config::getConfig(\haibao\classlibrary\jiepai\Config::LARGE_ARTICLE_PAGE_SIZE);
        }
        return $this->normalQuery($sql, array($userId));
    }

    public function getCommentInfo($commentId)
    {
        $sql = "SELECT t1.CommentID,t1.Content,t1.SensitiveWords,t1.CreateTime,t2.ReplyNum,t3.PraiseNum,t1.AuditStatus from cms_comment t1 " .
            "LEFT JOIN (SELECT CommentID,Count(*) as ReplyNum from cms_comment_reply WHERE CommentID = %s AND AuditStatus !=2 " .
            ") t2 on t1.CommentID = t2.CommentID " .
            "LEFT JOIN (SELECT TypeID,COUNT(*) as PraiseNum from cms_user_action WHERE TypeID = %s AND Type = 3 AND Flag = 0) t3 on t3.TypeID = t1.CommentID " .
            "WHERE t1.CommentID = %s;";

        $result = $this->query($sql, array_pad(array(), 3, $commentId))->fetch_assoc();

        $list = array(
            'CommentID' => $result['CommentID'],
            'Content' => $result['Content'],
            'CreateTime' => $result['CreateTime'],
            'IsPraise' => 0,
            'AuditStatus' => $result['AuditStatus'],
            'SensitiveWords' => $result['SensitiveWords'],
            'Statistic' => array(
                'ReplyNum' => $result['ReplyNum'] ? $result['ReplyNum'] : 0,
                'PraiseNum' => $result['PraiseNum'] ? $result['PraiseNum'] : 0,
            ),
        );


        return $list;
    }


    public function checkCommentReplyStatus($replyId)
    {
        $sql = "SELECT Flag,AuditStatus from cms_comment_reply WHERE ReplyID=" . $replyId;
        $result = $this->query($sql);
        $list = array();
        while ($row = $result->fetch_assoc()) {
            array_push($list, $row);
        }
        return (isset($list[0]) && $list[0]['Flag'] == 0 && $list[0]['AuditStatus'] != 2) ? true : false;
    }

    public function checkCommentStatus($commentId)
    {
        $sql = "SELECT Flag,AuditStatus from cms_comment WHERE CommentID=" . $commentId;
        $result = $this->query($sql);
        $list = array();
        while ($row = $result->fetch_assoc()) {
            array_push($list, $row);
        }
        return (isset($list[0]) && $list[0]['Flag'] == 0 && $list[0]['AuditStatus'] != 2) ? true : false;
    }

    public function replyCommentArticle($param, $commentId)
    {
        $sql = "INSERT INTO cms_comment_reply(RepliedID,UserID,ReplyTime,Content,CommentID,RepliedUserID,Status,AuditStatus,AuditTime,AuditUserID,SensitiveWords,Flag,IsBest) values (%s,%s,%s,%s,%s,%s,0,0,NULL,NULL,%s,0,0)";
        $this->query($sql, array(isset($param['RepliedID']) ? $param['RepliedID'] : null, $param['UserID'], date('Y-m-d H:i:s'), $param['Content'], $commentId, isset($param['RepliedUserID']) ? $param['RepliedUserID'] : NULL, $param['SensitiveWords']));
        return $this->getDb()->insert_id;
    }

    public function insertCommentArticle($params, $articleId, $ContentIndex)
    {
        $sql = "INSERT INTO cms_comment set Content=%s,Type=0,TypeID=%s,UserID=%s,SensitiveWords=%s,ContentIndex=%s";
        $this->query($sql, array($params['Content'], $articleId, $params['UserID'], $params['SensitiveWords'], $params['ContentIndex']));
        return $this->getDb()->insert_id;
    }

    /**
     * Type  1，评论文章   2，回复评论   7，评论图片 8，回复图片
     * 1,找出ToUserID和需要推送的内容   2,入库   3,统计未读数量  4,推送
     */
    public function pushCommentMsg($typeId, $type, $fromUserID, $flag = null)
    {
        $sql = '';
        if ($type == 1 || $type == 7) {
            $sql = 'SELECT a.EditorID as UserID FROM cms_comment c LEFT JOIN cms_articles a ON c.TypeID=a.ArticleID WHERE c.CommentID=%s';
        } elseif ($type == 2 || $type == 8) {
            if ($flag == 'replyToReply') {
                $sql = 'SELECT RepliedUserID as UserID FROM cms_comment_reply where ReplyID=%s';
            } else {
                $sql = 'SELECT c.UserID FROM cms_comment_reply r LEFT JOIN cms_comment c ON r.CommentID=c.CommentID WHERE r.ReplyID=%s';
            }
        }

        $result = $this->query($sql, array($typeId));
        $list = array();
        while ($row = $result->fetch_assoc()) {
            array_push($list, $row);
        }
        if (count($list) == 0) {
            return '';
        }
        $userId = $list[0]['UserID'];
        $checkList = self::checkUserIgnore($userId, $fromUserID);
        if (count($checkList) > 0) {
            return '';
        } else {
            $this->query('insert into cms_messages(UserID,TypeID,`Type`,FromUserID) values(%s,%s,%s,%s)', array(
                $userId, $typeId, $type, $fromUserID
            ));
            return $this->getDb()->insert_id;
        }
    }

    function checkUserIgnore($UserID, $IgnoreID)
    {
        $sql = 'select * from cms_messages_ignore where UserID=%s AND IgnoreID=%s';
        $result = $this->query($sql, array($UserID, $IgnoreID));
        $list = array();
        while ($row = $result->fetch_assoc()) {
            array_push($list, $row);
        }
        return $list;
    }

    public function getCommentCount(array $ids)
    {
        $existList = array();
        $str = preg_replace('/(\d+)/', '%s', implode(',', $ids));
        $result = $this->query('select distinct(TypeID),CommentID,count(*) as count from cms_comment where TypeID in (' . $str . ') and Flag=0 group by TypeID', $ids);
        if ($result) {
            while ($result->fetch_assoc()) {
                $result2 = $this->query('select count(*) as count from cms_comment_reply where CommentID in (select CommentID from cms_comment where TypeID=%s and Flag=0) and Flag=0', array(
                    $result->getData('TypeID')
                ))->fetch_assoc();
                $existList[$result->getData('TypeID')] = $result->getData('count') + (isset($result2['count']) ? intval($result2['count']) : 0);
            }
        }
        $commentResult = array();
        foreach ($ids as $key => $commentId) {
            $commentResult[$commentId] = isset($existList[$commentId]) ? $existList[$commentId] : 0;
        }
        return $commentResult;
    }

    public function insertCommentPictures($pictureIdArr, $type, $typeId)
    {
        if (!$pictureIdArr) {
            return false;
        }

        if (isset($pictureIdArr) && $pictureIdArr) {
            $sql = 'insert into cms_comment_pictures(PictureID,Type,`Index`,TypeID,Flag) values ';
            $arrSql = $arrValues = array();
            $i = 0;
            foreach ($pictureIdArr as $key => $val) {
                array_push($arrSql, '(%s,%s,%s,%s,%s)');
                array_push($arrValues, $val);
                array_push($arrValues, $type);
                array_push($arrValues, $i);
                array_push($arrValues, $typeId);
                array_push($arrValues, 0);
                $i++;
            }
            if ($arrSql && $arrValues) {
                $sql .= implode(',', $arrSql);
                $this->query($sql, $arrValues);
            }
        }
    }

    /**
     * 回复评论或回复回复的评论
     * @param $data
     * @param $commentId
     * @return mixed
     */
    public function replyComment($data)
    {
        $this->query('insert into cms_comment_reply(Content, RepliedID, RepliedUserID, CommentID, UserID, SensitiveWords) values(%s,%s,%s,%s,%s,%s)', array(
            $data['Content'], $data['RepliedID'], $data['RepliedUserID'], $data['CommentId'], $data['UserID'], $data['SensitiveWords']
        ));
        return $this->getDb()->insert_id;
    }

    /**
     * 保存评论内容
     * @param $commentData
     * @return mixed
     */
    public function saveComment($commentData)
    {
        $this->query('insert into cms_comment(Content, `Type`, TypeID, UserID, SensitiveWords, ContentIndex) values(%s,%s,%s,%s,%s,%s)', array(
            $commentData['Content'], $commentData['Type'], $commentData['TypeID'], $commentData['UserID'], $commentData['SensitiveWords'], $commentData['ContentIndex']
        ));
        return $this->getDb()->insert_id;
    }

    /**
     * 保存评论图片对应关系
     */
    public function saveCommentPicture($pictureList, $type, $typeID)
    {
        if (!$pictureList) {
            return false;
        }
        $sql = 'insert into cms_comment_pictures(PictureID, `Type`, Index, TypeID, ) values';
        foreach ($pictureList as $key => $value) {
            $sql .= "($value, $type, $key, $typeID),";
        }
        $this->query(rtrim($sql, ','));
    }

    public function getAllQuickCommentList()
    {
        $result = $this->query('select * from cms_comment_quick where Flag=0');
        $quickList = array();
        while ($row = $result->fetch_assoc()) {
            array_push($quickList, $row);
        }
        return $quickList;
    }

    /**
     * 获取快速评论列表
     */
    public function quickCommentList()
    {
        $cache = new \haibao\jiepai\cache\Comment();
        $quickList = $cache->getQuickCommentList();
        if (!$quickList) {
            $result = $this->query('select * from cms_comment_quick where Flag=0');
            $quickList = array();
            $list = array();
            while ($row = $result->fetch_assoc()) {
                array_push($list, $row['Content']);
                array_push($quickList, $row);
            }
            $quickList = array_rand(array_flip($list), 15);
            $cache->setQuickCommentList($quickList, $this->getTodayRemainSecond());
        }
        return $quickList;
    }

    /**
     * 保存快速评论
     */
    public function saveQucikComment($content)
    {
        $this->query('insert into cms_comment_quick(Content,CreateTime,Flag) value(%s,%s,%s)', array(
            $content, date('Y-m-d H:i:s'), 0
        ));
        return $this->getDb()->insert_id;
    }

    /**
     * 删除快速评论
     */
    public function deleteQuickComment($quickId)
    {
        $this->query('update cms_comment_quick set Flag=-1 where ID=%s', array($quickId));
    }

    /**
     * 获取今天剩余秒数
     */
    private function getTodayRemainSecond()
    {
        $time = time();
        $todayEndTime = strtotime(date('Y-m-d', strtotime('+1 day')) . ' 00:00:00');
        return (int)($todayEndTime - $time);
    }
}